/*
 * Copyright (C) 2018 Baidu, Inc. All Rights Reserved.
 */
package com.hongye.jpademo;

import java.util.Set;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

@Service
@Validated
public class UserServer {

    @Resource
    private UserRepo userRepo;

    @Resource
    private Validator validator;

    /**
     * 收工校验
     *
     * @param addForm
     *
     * @return
     */
    public Boolean addUserManualValidate(UserAddForm addForm) {
        Set<ConstraintViolation<UserAddForm>> violations = validator.validate(addForm);
        if (violations != null && violations.size() > 0) {
            System.out.println(violations);
            ConstraintViolation cv = (ConstraintViolation) violations.toArray()[0];
            System.out.println(cv.getMessage());
            throw new RuntimeException(cv.getMessage());
        }
        User newUser = addForm.toUser();
        User result = userRepo.save(newUser);
        return result != null;
    }

    /**
     * 系统校验
     *
     * @param addForm
     *
     * @return
     */
    public Boolean addUserSystemValidate(@Valid UserAddForm addForm) {
        User newUser = addForm.toUser();
        User result = userRepo.save(newUser);
        return result != null;
    }
}
